# 该脚本用于K均值聚类确定聚类的个数
import pylab as plt
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
import Image

# 离差平方和拐点法和轮廓系数法
# 输入的变量需要是消除量纲影响的数据
def Judge_K(data, title='', draw=True):
    if draw:
        print('正在确定K均值聚类最佳确定聚类的个数......')
        # 默认聚类成2到15个类
        Nums = range(2, 15)
        SSE = []
        Factor = []
        for i in Nums:
            Md = KMeans(i).fit(data)
            labels = Md.labels_
            # 离差平方和
            SSE.append(Md.inertia_)
            # 轮廓系数
            Factor.append(silhouette_score(data, labels))
        # 画图
        plt.figure()
        plt.title(title+'离差平方和拐点法')
        plt.plot(Nums, SSE, '*-')
        # Image.KeepImage(title+'离差平方和拐点法',Keep=KeepDraw,ImageTitle=title+'离差平方和拐点法')
        plt.figure()
        plt.title(title+'轮廓系数法')
        plt.plot(Nums, Factor, 'o-')
        # Image.KeepImage(title+'轮廓系数法',Keep=KeepDraw,ImageTitle=title+'轮廓系数法')
